<?php

namespace App\Http\Controllers;

use App\Models\Good;
use App\Models\Order;
use App\Models\LoginTime;
use Illuminate\Http\Request;

class GoodController extends Controller
{
    public function index (Request $request)
    {
        $user = $request->user;
        $order = Order::query ()->where ("uid", $user["id"])->whereDate ('created_at', now ()->toDateString ())->first ();
        $goods = Good::query ()->get ()->toArray ();
        return $this->success (["order" => $order, "good" => $goods], "获取成功");
    }

    public function store (Request $request)
    {
        $login_time = LoginTime::query ()->first ();
        if ($login_time) {
            $current_time = date ('H:i:s');
            $start_datetime = \DateTime::createFromFormat ('H:i:s', $login_time->start_time);
            $end_datetime = \DateTime::createFromFormat ('H:i:s', $login_time->end_time);
            $current_datetime = \DateTime::createFromFormat ('H:i:s', $current_time);
            if ($current_datetime < $start_datetime || $current_datetime > $end_datetime) {
                return $this->error ("当前时间不在选餐时间");
            }
        }
        $user = $request->user;
        $order = Order::query ()->where ("uid", $user["id"])->whereDate ('created_at', now ()->toDateString ())->first ();
        if ($order) {
            return $this->error ("你今日已选择");
        }
        $goods_name = $request->input ("goods_name");
        $order = new Order();
        $order->uid = $user['id'];
        $order->department_id = $user["department_id"];
        $order->goods_name = $goods_name;
        if ($order->save ()) {
            return $this->success ("", "添加成功");
        } else {
            return $this->error ("添加失败");
        }
    }

    public function userInfo (Request $request)
    {
        $user = $request->user;
        return $this->success ($user, "获取成功");
    }
}
